<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ficon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/icon.png">
  <link rel="mask-icon" href="/images/icon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bqlin.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":{"gitalk":{"order":-2}},"activeClass":"gitalk"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="每当你与底层系统打交道时，必须准备好该任务可能需要花费大量的时间。对内核或其他系统层的调用涉及到上下文的改变，与发生在进程中的调用相比，这种改变是相当昂贵的。因此，许多系统库提供了异步接口，允许你的代码向系统提交一个请求，并在处理该请求时继续做其他工作。Grand Central Dispatch建立在这种一般行为的基础上，允许你提交请求，并使用block和调度队列将结果反馈给你的代码。">
<meta property="og:type" content="article">
<meta property="og:title" content="Concurrency Programming Guide：调度源">
<meta property="og:url" content="https://bqlin.github.io/posts/concurrency_pg_dispatch_sources/index.html">
<meta property="og:site_name" content="權咚领域">
<meta property="og:description" content="每当你与底层系统打交道时，必须准备好该任务可能需要花费大量的时间。对内核或其他系统层的调用涉及到上下文的改变，与发生在进程中的调用相比，这种改变是相当昂贵的。因此，许多系统库提供了异步接口，允许你的代码向系统提交一个请求，并在处理该请求时继续做其他工作。Grand Central Dispatch建立在这种一般行为的基础上，允许你提交请求，并使用block和调度队列将结果反馈给你的代码。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-08T09:43:58.000Z">
<meta property="article:modified_time" content="2021-10-24T04:12:53.000Z">
<meta property="article:author" content="權咚">
<meta property="article:tag" content="Apple">
<meta property="article:tag" content="多线程">
<meta property="article:tag" content="Concurrency Programming Guide">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bqlin.github.io/posts/concurrency_pg_dispatch_sources/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Concurrency Programming Guide：调度源 | 權咚领域</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-105338942-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-105338942-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?98fcf61fd269408d07dcbc1e49311f9a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="權咚领域" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">權咚领域</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Making app a work of art.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bqlin.github.io/posts/concurrency_pg_dispatch_sources/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/icon.png">
      <meta itemprop="name" content="權咚">
      <meta itemprop="description" content="🤘🤯👾">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="權咚领域">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Concurrency Programming Guide：调度源
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-09-08 17:43:58" itemprop="dateCreated datePublished" datetime="2021-09-08T17:43:58+08:00">2021-09-08</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-24 12:12:53" itemprop="dateModified" datetime="2021-10-24T12:12:53+08:00">2021-10-24</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%BF%BB%E8%AF%91/" itemprop="url" rel="index"><span itemprop="name">翻译</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>15k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>14 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>每当你与底层系统打交道时，必须准备好该任务可能需要花费大量的时间。对内核或其他系统层的调用涉及到上下文的改变，与发生在进程中的调用相比，这种改变是相当昂贵的。因此，许多系统库提供了异步接口，允许你的代码向系统提交一个请求，并在处理该请求时继续做其他工作。Grand Central Dispatch建立在这种一般行为的基础上，允许你提交请求，并使用block和调度队列将结果反馈给你的代码。</p>
<span id="more"></span>
<h2 id="关于调度源">关于调度源</h2>
<p><em>调度源</em>是一个基本的数据类型，它协调特定的底层系统事件的处理。Grand Central Dispatch支持以下类型的调度源：</p>
<ul>
<li><em>计时器调度源</em>产生定期通知。</li>
<li><em>信号调度源</em>在UNIX信号到达时发出通知。</li>
<li><em>描述符源</em>通知你各种基于文件和套接字的操作，例如：
<ul>
<li>当数据可供读取时；</li>
<li>当可以写入数据时；</li>
<li>当文件在文件系统中被删除、移动或重命名时；</li>
<li>当文件元信息发生变化时；</li>
</ul></li>
<li><em>进程调度源</em>通知你与进程有关的事件，如：
<ul>
<li>当一个进程退出时；</li>
<li>当一个进程发出一个<code>fork</code>或<code>exec</code>类型的调用时；</li>
<li>当一个信号被传递给进程时；</li>
</ul></li>
<li><em>机器端口调度源</em>通知与机器有关的事件。</li>
<li><em>自定义调度源</em>可以由自己定义和触发。</li>
</ul>
<p>调度源取代通常用于处理系统相关事件的异步回调函数。当你配置一个调度源时，指定你想监控的事件和调度队列，以及用来处理这些事件的代码。你可以使用block对象或函数指定你的代码。当一个感兴趣的事件到来时，调度源会将你的block或函数提交给指定的调度队列来执行。</p>
<p>与手动提交到队列的任务不同，调度源为程序提供了一个持续的事件源。在你明确取消它之前，一个调度源一直连接到它的调度队列。在连接期间，每当相应的事件发生时，它都会向调度队列提交其相关的任务代码。有些事件，如定时器事件，会定期发生，但大多数事件只是在特定条件出现时零星地发生。出于这个原因，调度源保留其相关的调度队列，以防止它在事件可能仍在等待时被过早释放。</p>
<p>为了防止事件积压在调度队列中，调度源实施了一个事件合并（coalescing）方案。如果一个新的事件在前一个事件的handler被取消排队并执行之前到达，调度源就会将新的事件数据与旧事件的数据合并起来。根据事件的类型，合并可能会取代旧事件或更新其持有的信息。例如，一个基于信号的调度源只提供关于最近的信号信息，但也报告自上次调用事件handler以来，总共有多少信号被传递。</p>
<h2 id="创建调度源">创建调度源</h2>
<p>创建一个调度源包括创建事件源和调度源本身。事件源是处理这些事件所需的任何本地数据结构。例如，对于一个基于描述符的调度源，你需要打开描述符，而对于一个基于进程的源，你需要获得目标程序的进程ID。当你有了你的事件源，你就可以按以下方法创建相应的调度源：</p>
<ol type="1">
<li>使用 <code>dispatch_source_create</code> 函数创建调度源。</li>
<li>配置调度源：
<ul>
<li>为调度源分配一个事件handler；可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW13">Writing and Installing an Event Handler</a>。</li>
<li>对于定时器源，使用<code>dispatch_source_set_timer</code>函数设置定时器信息；可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW2">Creating a Timer</a>。</li>
</ul></li>
<li>可以选择给调度源分配一个取消handler；可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW14">Installing a Cancellation Handler</a>。</li>
<li>调用<code>dispatch_resume</code>函数开始处理事件；可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW8">Suspending and Resuming Dispatch Sources</a>。</li>
</ol>
<p>由于调度源在使用前需要一些额外的配置，<code>dispatch_source_create</code>函数在暂停状态下返回调度源。在暂停状态下，调度源接收事件但不处理它们。这使你有时间配置一个事件handler，并执行处理实际事件所需的其他配置。</p>
<p>下面的章节向你展示了如何配置调度源。关于展示如何配置特定类型的调度源的详细例子，可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW22">Dispatch Source Examples</a>。关于用来创建和配置调度源的函数的其他信息，可参阅<em>Grand Central Dispatch (GCD) Reference</em>。</p>
<h3 id="编写和配置一个事件handler">编写和配置一个事件Handler</h3>
<p>为了处理由调度源产生的事件，你必须定义一个事件handler来处理这些事件。事件handler是一个函数或block对象，用<code>dispatch_source_set_event_handler</code>或<code>dispatch_source_set_event_handler_f</code>函数将其配置在调度源上。当一个事件到来时，调度源会将事件handler提交给指定的调度队列进行处理。</p>
<p>你的事件handler的主体负责处理任何到达的事件。如果你的事件handler已经在队列中并等待处理一个事件，当一个新的事件到达时，调度源会将这两个事件合并起来。一个事件handler通常只看到最近的事件的信息，但根据调度源的类型，它也可以获得其他已经发生并被合并的事件的信息。如果一个或多个新的事件在事件handler开始执行后到达，调度源会保留这些事件，直到当前事件handler执行完毕。这时，它将事件handler与新的事件一起再次提交给队列。</p>
<p>基于函数的事件handler接受一个单一的上下文指针，包含调度源对象，并且不返回任何值。基于block的事件handler不接受参数，也没有返回值。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Block-based event handler</span></span><br><span class="line"><span class="keyword">void</span> (^dispatch_block_t)(<span class="keyword">void</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// Function-based event handler</span></span><br><span class="line"><span class="keyword">void</span> (*dispatch_function_t)(<span class="keyword">void</span> *)</span><br></pre></td></tr></table></figure>
<p>在事件handler中，你可以从调度源本身获得关于给定事件的信息。尽管基于函数的事件handler被传递一个指向调度源的指针作为参数，但基于block的事件handler必须自己捕获这个指针。你可以通过正常引用包含调度源的变量来实现捕获指针。例如，下面的代码片段捕获了<code>source</code>变量，它被声明在block的范围之外。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,</span><br><span class="line">                                 myDescriptor, <span class="number">0</span>, myQueue);</span><br><span class="line">dispatch_source_set_event_handler(source, ^&#123;</span><br><span class="line">   <span class="comment">// Get some data from the source variable, which is captured</span></span><br><span class="line">   <span class="comment">// from the parent context.</span></span><br><span class="line">   size_t estimated = dispatch_source_get_data(source);</span><br><span class="line"> </span><br><span class="line">   <span class="comment">// Continue reading the descriptor...</span></span><br><span class="line">&#125;);</span><br><span class="line">dispatch_resume(source);</span><br></pre></td></tr></table></figure>
<p>在block内捕获变量通常是为了获得更大的灵活性和动态性。当然，捕获的变量在block内默认为只读。尽管block功能提供了对特定情况下修改捕获变量的支持，但你不应该试图在与调度源相关的事件handler中这样做。调度源总是异步地执行它们的事件handler，所以当你的事件handler执行时，你捕获的任何变量的定义作用域很可能已经消失。关于如何在block内捕获和使用变量的更多信息，可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html#//apple_ref/doc/uid/TP40007502">Blocks Programming Topics</a>。</p>
<p>表4-1列出了可以从事件handler代码中调用的函数，以获取事件的信息。</p>
<p><strong>Table 4-1</strong> 从调度源获取数据</p>
<p><code>dispatch_source_get_handle</code>：该函数返回调度源所管理的底层系统数据类型。</p>
<ul>
<li>对于描述符调度源，该函数返回一个包含与调度源相关的描述符的<code>int</code>类型。</li>
<li>对于一个信号调度源，该函数返回一个<code>int</code>类型，包含最近事件的信号编号。</li>
<li>对于一个进程调度源，此函数返回一个<code>pid_t</code>数据结构，用于被监控的进程。</li>
<li>对于一个Mach端口调度源，此函数返回一个<code>mach_port_t</code>数据结构。</li>
<li>对于其他调度源，此函数返回的值是未定义的。</li>
</ul>
<p><code>dispatch_source_get_data</code> ：此函数返回与事件相关的任何未决（pending）数据。</p>
<ul>
<li><p>对于从文件中读取数据的描述符调度源，该函数返回可供读取的字节数。</p></li>
<li><p>对于向文件写数据的描述符调度源，如果有空间可供写入，该函数返回一个正整数。</p></li>
<li><p>对于监视文件系统活动的描述符调度源，该函数返回一个<code>dispatch_source_vnode_flags_t</code>枚举，表示所发生的事件的类型。</p></li>
<li><p>对于一个进程调度源，这个函数返回一个<code>dispatch_source_proc_flags_t</code>枚举，表示发生的事件类型。</p></li>
<li><p>对于Mach端口调度源，此函数返回一个<code>dispatch_source_machport_flags_t</code>枚举，表示发生的事件类型。</p></li>
<li><p>对于自定义调度源，此函数返回从现有数据和传递给<code>dispatch_source_merge_data</code>函数的新数据创建的新数据值。</p></li>
</ul>
<p><code>dispatch_source_get_mask</code>：该函数返回用于创建调度源的事件标志。</p>
<ul>
<li><p>对于一个进程调度源，该函数返回调度源所接收的事件的掩码（<code>dispatch_source_proc_flags_t</code>）。</p></li>
<li><p>对于具有发送权限的Mach端口调度源，此函数返回所需事件的掩码（<code>dispatch_source_mach_send_flags_t</code>）。</p></li>
<li><p>对于一个自定义OR调度源，此函数返回用于合并数据值的掩码。</p></li>
</ul>
<p>关于如何为特定类型的调度源编写和配置事件handler的例子，可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW22">Dispatch Source Examples</a>。</p>
<h3 id="配置取消handler">配置取消Handler</h3>
<p>取消handler用于在调度源被释放之前对其进行清理。对于大多数类型的调度源，取消handler是可选的，只有当你有一些与调度源绑定的自定义行为也需要被更新时才有必要。然而，对于使用描述符或Mach端口的调度源，你必须提供一个取消handler来关闭描述符或释放Mach端口。如果不这样做，这些结构体被你的代码和系统的其他部分无意地重用，可能会导致代码中出现微妙的错误。</p>
<p>可以在任何时候配置取消handler，但通常在创建调度源时进行配置。你可以使用<code>dispatch_source_set_cancel_handler</code>或<code>dispatch_source_set_cancel_handler_f</code>函数来配置取消handler，这取决于你想在实现中使用一个block对象还是一个函数。下面的例子显示了一个简单的取消handler，它关闭了一个为调度源打开的描述符。<code>fd</code>变量是一个包含描述符的捕获变量。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dispatch_source_set_cancel_handler(mySource, ^&#123;</span><br><span class="line">   close(fd); <span class="comment">// Close a file descriptor opened earlier.</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="修改目标队列">修改目标队列</h3>
<p>尽管你在创建调度源时指定了运行事件和取消handler的队列，但你可以在任何时候使用 <code>dispatch_set_target_queue</code> 函数改变该队列。通过这样你可以改变调度源的事件处理的优先级。</p>
<p>修改调度源的队列是一个异步操作，调度源会尽最大努力尽快做出修改。如果一个事件handler已经在队列中并等待处理，它将在之前的队列中执行。然而，在你修改的时候，其他到达的事件可以在任一队列中处理。</p>
<h3 id="关联自定义数据与调度源">关联自定义数据与调度源</h3>
<p>像Grand Central Dispatch中的许多其他数据类型一样，你可以使用<code>dispatch_set_context</code>函数来将自定义数据与调度源关联起来。可以使用上下文指针来存储事件handler在处理事件时需要的任何数据。如果你确实在上下文指针中存储了任何自定义数据，你也应该设置一个取消handler，以便在不再需要调度源时释放这些数据。</p>
<p>如果你使用block来实现你的事件handler，也可以捕获局部变量并在基于block的代码中使用它们。尽管这可能减轻了在调度源的上下文指针中存储数据的需要，但你应该始终谨慎地使用这一功能。因为调度源在程序中可能是长期存在的，在捕获包含指针的变量时应该小心。如果指针所指向的数据在任何时候都可能被释放，你应该复制该数据或保留它。在这两种情况下，你都需要配置一个取消handler来释放这些数据。</p>
<h3 id="调度源的内存管理">调度源的内存管理</h3>
<p>像其他调度对象一样，调度源也是有引用计数的数据类型。一个调度源的初始引用计数为1，可以使用<code>dispatch_retain</code>和<code>dispatch_release</code>函数保留和释放。当一个队列的引用计数达到0时，系统会自动释放调度源的数据结构。</p>
<p>由于它们的使用方式，调度源的所有权可以由内部管理，也可以由外部管理。对于外部所有权，另一个对象或一段代码拥有调度源的所有权，并负责在不再需要它时将其释放。对于内部所有权，调度源持有自己，并负责在适当的时候释放自己。尽管外部所有权非常普遍，但在你想创建一个自主的调度源并让它管理你的代码的某些行为而不进行任何进一步的交互的情况下，你可能会使用内部所有权。例如，如果一个调度源被设计为响应一个单一的全局事件，你可能会让它处理该事件，然后立即退出。</p>
<h2 id="调度源示例">调度源示例</h2>
<p>下面的章节向你展示了如何创建和配置一些更常用的调度源。关于配置特定类型的调度源的更多信息，可参阅<em>Grand Central Dispatch (GCD) Reference</em>。</p>
<h3 id="创建定时器">创建定时器</h3>
<p>定时器调度源以定期、基于时间的间隔产生事件。你可以使用定时器来启动需要定期执行的特定任务。例如，游戏和其他图形密集型的程序可以使用定时器来启动屏幕或动画的更新。你也可以设置一个定时器并使用产生的事件来检查经常更新的服务器上的新信息。</p>
<p>所有的定时器调度源都是间隔性的定时器，也就是说，一旦创建，它们就会按照你指定的时间间隔定期发送事件。当你创建一个定时器调度源时，你必须指定的一个值是一个leeway值，以使系统知道定时器事件的所需精度。leeway值让系统在如何管理电源和唤醒内核方面有一定的灵活性。例如，系统可能会使用leeway值来提前或推迟启动时间，并使其与其他系统事件更好地协调。因此，你应该尽可能为你自己的定时器指定一个leeway值。</p>
<p><strong>注意：</strong>即使你指定了一个0的leeway值，你也不应该期望定时器在你要求的精确纳秒处启动。系统会尽力满足你的需求，但不能保证精确的启动时间。</p>
<p>当计算机进入睡眠状态时，所有的定时器调度源都被暂停。当计算机唤醒时，这些定时器调度源也会被自动唤醒。根据定时器的配置，这种性质的暂停可能会影响定时器下一次触发的时间。如果你使用<code>dispatch_time</code>函数或<code>DISPATCH_TIME_NOW</code>常数来设置你的定时器调度源，定时器调度源会使用默认的系统时钟来决定何时启动。然而，当计算机处于睡眠状态时，默认的时钟不会前进。相比之下，当你使用<code>dispatch_walltime</code>函数设置你的定时器调度源时，定时器调度源会跟踪其触发时间到绝对（wall）的时钟时间。后者通常适用于触发间隔比较大的定时器，因为它可以防止事件时间之间有太大的漂移。</p>
<p>清单4-1显示了一个定时器的例子，它每30秒触发一次，leeway为1秒。因为定时器的时间间隔比较大，所以使用<code>dispatch_walltime</code>函数来创建调度源。计时器的第一次触发立即发生，随后的事件每30秒到达。<code>MyPeriodicTask</code>和<code>MyStoreTimer</code>符号代表自定义函数，编写这些函数来实现定时器行为，并将定时器存储在程序数据结构的某个地方。</p>
<p>下面展示了一个间隔 30s leeaway 1s 的timer。因为间隔较大，dispatch source 使用 <code>dispatch_walltime</code> 来创建的。timer 初次会立即 fire，之后每 30s 到达一次。</p>
<p><strong>清单4-1</strong> 创建定时器数据源</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">dispatch_source_t CreateDispatchTimer(uint64_t interval,</span><br><span class="line">              uint64_t leeway,</span><br><span class="line">              <span class="built_in">dispatch_queue_t</span> queue,</span><br><span class="line">              dispatch_block_t block)</span><br><span class="line">&#123;</span><br><span class="line">   dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,</span><br><span class="line">                                                     <span class="number">0</span>, <span class="number">0</span>, queue);</span><br><span class="line">   <span class="keyword">if</span> (timer)</span><br><span class="line">   &#123;</span><br><span class="line">      dispatch_source_set_timer(timer, dispatch_walltime(<span class="literal">NULL</span>, <span class="number">0</span>), interval, leeway);</span><br><span class="line">      dispatch_source_set_event_handler(timer, block);</span><br><span class="line">      dispatch_resume(timer);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> timer;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">void</span> MyCreateTimer()</span><br><span class="line">&#123;</span><br><span class="line">   dispatch_source_t aTimer = CreateDispatchTimer(<span class="number">30</span>ull * <span class="built_in">NSEC_PER_SEC</span>,</span><br><span class="line">                               <span class="number">1</span>ull * <span class="built_in">NSEC_PER_SEC</span>,</span><br><span class="line">                               dispatch_get_main_queue(),</span><br><span class="line">                               ^&#123; MyPeriodicTask(); &#125;);</span><br><span class="line"> </span><br><span class="line">   <span class="comment">// Store it somewhere for later use.</span></span><br><span class="line">    <span class="keyword">if</span> (aTimer)</span><br><span class="line">    &#123;</span><br><span class="line">        MyStoreTimer(aTimer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>尽管创建一个定时器调度源是接收基于时间的事件的主要方式，但也有其他选择。如果你想在指定的时间间隔后执行一次block，你可以使用<code>dispatch_after</code>或<code>dispatch_after_f</code>函数。这个函数的作用与<code>dispatch_async</code>函数很相似，只是它允许你指定一个时间值，在这个时间值上将block提交给队列。根据你的需要，时间值可以指定为一个相对的或绝对的时间值。</p>
<h3 id="从描述符中读取数据">从描述符中读取数据</h3>
<p>要从文件或套接字中读取数据，你必须打开文件或套接字，并创建一个<code>DISPATCH_SOURCE_TYPE_READ</code>类型的调度源。指定的事件handler应该能够读取和处理文件描述符的内容。在处理文件的情况下，这相当于读取文件数据（或该数据的一个子集），并为程序创建适当的数据结构。对于网络套接字，这涉及到处理新收到的网络数据。</p>
<p>每当读取数据时，你应该始终将描述符配置为使用非阻塞操作。尽管可以使用<code>dispatch_source_get_data</code>函数来查看有多少数据可供读取，但该函数返回的值在你调用时和你实际读取数据时可能发生变化。如果底层文件被截断或发生网络错误，从描述符中读取的数据会阻塞当前线程，从而使你的事件handler在执行过程中卡死，阻塞调度队列其他任务。对于一个串行队列，这可能会使队列造成死锁，甚至对于一个并发队列，这也会削减可启动的新任务的数量。</p>
<p>清单4-2显示了一个配置调度源以从文件中读取数据的例子。在这个例子中，事件handler将指定文件的全部内容读入一个缓冲区，并调用一个自定义函数来处理这些数据。该函数的调用者将使用返回的调度源，在读取操作完成后取消它。为了确保调度队列在没有数据可读时不会出现不必要的阻塞，本例使用<code>fcntl</code>函数来配置文件描述符，使其执行非阻塞操作。配置在调度源上的取消handler确保文件描述符在数据被读取后被关闭。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">dispatch_source_t ProcessContentsOfFile(<span class="keyword">const</span> <span class="keyword">char</span>* filename)</span><br><span class="line">&#123;</span><br><span class="line">   <span class="comment">// Prepare the file for reading.</span></span><br><span class="line">   <span class="keyword">int</span> fd = open(filename, O_RDONLY);</span><br><span class="line">   <span class="keyword">if</span> (fd == <span class="number">-1</span>)</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">   fcntl(fd, F_SETFL, O_NONBLOCK);  <span class="comment">// Avoid blocking the read operation</span></span><br><span class="line"> </span><br><span class="line">   <span class="built_in">dispatch_queue_t</span> queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>);</span><br><span class="line">   dispatch_source_t readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,</span><br><span class="line">                                   fd, <span class="number">0</span>, queue);</span><br><span class="line">   <span class="keyword">if</span> (!readSource)</span><br><span class="line">   &#123;</span><br><span class="line">      close(fd);</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">   <span class="comment">// Install the event handler</span></span><br><span class="line">   dispatch_source_set_event_handler(readSource, ^&#123;</span><br><span class="line">      size_t estimated = dispatch_source_get_data(readSource) + <span class="number">1</span>;</span><br><span class="line">      <span class="comment">// Read the data into a text buffer.</span></span><br><span class="line">      <span class="keyword">char</span>* buffer = (<span class="keyword">char</span>*)malloc(estimated);</span><br><span class="line">      <span class="keyword">if</span> (buffer)</span><br><span class="line">      &#123;</span><br><span class="line">         ssize_t actual = read(fd, buffer, (estimated));</span><br><span class="line">         Boolean done = MyProcessFileData(buffer, actual);  <span class="comment">// Process the data.</span></span><br><span class="line"> </span><br><span class="line">         <span class="comment">// Release the buffer when done.</span></span><br><span class="line">         free(buffer);</span><br><span class="line"> </span><br><span class="line">         <span class="comment">// If there is no more data, cancel the source.</span></span><br><span class="line">         <span class="keyword">if</span> (done)</span><br><span class="line">            dispatch_source_cancel(readSource);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"> </span><br><span class="line">   <span class="comment">// Install the cancellation handler</span></span><br><span class="line">   dispatch_source_set_cancel_handler(readSource, ^&#123;close(fd);&#125;);</span><br><span class="line"> </span><br><span class="line">   <span class="comment">// Start reading the file.</span></span><br><span class="line">   dispatch_resume(readSource);</span><br><span class="line">   <span class="keyword">return</span> readSource;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的例子中，自定义的<code>MyProcessFileData</code>函数决定了什么时候已经读取了足够的文件数据，什么时候取消调度源。默认情况下，为从描述符中读取数据而配置的调度源会在仍有数据需要读取时重复调度其事件handler。如果套接字连接关闭或到达文件的末尾，调度源会自动停止调度事件handler。如果确定不需要一个调度源，可以自己直接取消它。</p>
<h3 id="把数据写入描述符中">把数据写入描述符中</h3>
<p>向文件或套接字写数据的过程与读数据的过程非常相似。在为写操作配置描述符后，你要创建一个<code>DISPATCH_SOURCE_TYPE_WRITE</code>类型的调度源。一旦该调度源被创建，系统就会调用你的事件handler，让它有机会开始向文件或套接字写入数据。当你写完数据后，使用<code>dispatch_source_cancel</code>函数来取消调度源。</p>
<p>无论什么时候写数据，你都应该将文件描述符配置为使用非阻塞操作。尽管你可以使用<code>dispatch_source_get_data</code>函数来查看有多少空间可供写入，但该函数返回的值只是指导性的，在你调用时和你实际写入数据时可能发生变化。如果发生错误，向一个阻塞的文件描述符写入数据可能会使你的事件handler在执行过程中卡死，并阻塞调度队列其他任务。对于一个串行队列，这可能会使你的队列造成死锁，甚至对于一个并发队列，这也会削减可以启动的新任务的数量。</p>
<p>清单4-3显示了使用调度源向文件写入数据的基本方法。在创建新文件后，该函数将产生的文件描述符传递给其事件handler。被放入文件的数据是由<code>MyGetData</code>函数提供的，你可以用需要的任何代码来替换它，以生成文件的数据。将数据写入文件后，事件handler取消了调度源，以防止它被再次调用。然后，调度源的所有者将负责释放它。</p>
<p><strong>清单4-3</strong> 向文件写入数据</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">dispatch_source_t WriteDataToFile(<span class="keyword">const</span> <span class="keyword">char</span>* filename)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span> fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,</span><br><span class="line">                      (S_IRUSR | S_IWUSR | S_ISUID | S_ISGID));</span><br><span class="line">    <span class="keyword">if</span> (fd == <span class="number">-1</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">    fcntl(fd, F_SETFL); <span class="comment">// Block during the write.</span></span><br><span class="line"> </span><br><span class="line">    <span class="built_in">dispatch_queue_t</span> queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>);</span><br><span class="line">    dispatch_source_t writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE,</span><br><span class="line">                            fd, <span class="number">0</span>, queue);</span><br><span class="line">    <span class="keyword">if</span> (!writeSource)</span><br><span class="line">    &#123;</span><br><span class="line">        close(fd);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    dispatch_source_set_event_handler(writeSource, ^&#123;</span><br><span class="line">        size_t bufferSize = MyGetDataSize();</span><br><span class="line">        <span class="keyword">void</span>* buffer = malloc(bufferSize);</span><br><span class="line"> </span><br><span class="line">        size_t actual = MyGetData(buffer, bufferSize);</span><br><span class="line">        write(fd, buffer, actual);</span><br><span class="line"> </span><br><span class="line">        free(buffer);</span><br><span class="line"> </span><br><span class="line">        <span class="comment">// Cancel and release the dispatch source when done.</span></span><br><span class="line">        dispatch_source_cancel(writeSource);</span><br><span class="line">    &#125;);</span><br><span class="line"> </span><br><span class="line">    dispatch_source_set_cancel_handler(writeSource, ^&#123;close(fd);&#125;);</span><br><span class="line">    dispatch_resume(writeSource);</span><br><span class="line">    <span class="keyword">return</span> (writeSource);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="监控文件系统对象">监控文件系统对象</h3>
<p>如果你想监视一个文件系统对象的变化，你可以设置一个<code>DISPATCH_SOURCE_TYPE_VNODE</code>类型的调度源。你可以使用这种类型的调度源，在文件被删除、写入或重命名时接收通知。你也可以用它在文件的特定类型的元信息（如它的大小和链接数）发生变化时得到通知。</p>
<p><strong>注意：</strong>你为调度源指定的文件描述符必须在源本身处理事件时保持打开。</p>
<p>清单4-4显示了一个例子，它监视一个文件名变化，并在它发生变化时执行一些自定义行为。(你可以提供实际的行为来代替例子中调用的 <code>MyUpdateFileName</code> 函数。)因为一个描述符是专门为调度源打开的，所以调度源包含一个关闭描述符的取消handler。因为本例创建的文件描述符与底层文件系统对象相关联，相同的调度源可以用来检测任何数量的文件名变化。</p>
<p><strong>清单4-4</strong> 观察文件名变化</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">dispatch_source_t MonitorNameChangesToFile(<span class="keyword">const</span> <span class="keyword">char</span>* filename)</span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">int</span> fd = open(filename, O_EVTONLY);</span><br><span class="line">   <span class="keyword">if</span> (fd == <span class="number">-1</span>)</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line"> </span><br><span class="line">   <span class="built_in">dispatch_queue_t</span> queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>);</span><br><span class="line">   dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,</span><br><span class="line">                fd, DISPATCH_VNODE_RENAME, queue);</span><br><span class="line">   <span class="keyword">if</span> (source)</span><br><span class="line">   &#123;</span><br><span class="line">      <span class="comment">// Copy the filename for later use.</span></span><br><span class="line">      <span class="keyword">int</span> length = strlen(filename);</span><br><span class="line">      <span class="keyword">char</span>* newString = (<span class="keyword">char</span>*)malloc(length + <span class="number">1</span>);</span><br><span class="line">      newString = strcpy(newString, filename);</span><br><span class="line">      dispatch_set_context(source, newString);</span><br><span class="line"> </span><br><span class="line">      <span class="comment">// Install the event handler to process the name change</span></span><br><span class="line">      dispatch_source_set_event_handler(source, ^&#123;</span><br><span class="line">            <span class="keyword">const</span> <span class="keyword">char</span>*  oldFilename = (<span class="keyword">char</span>*)dispatch_get_context(source);</span><br><span class="line">            MyUpdateFileName(oldFilename, fd);</span><br><span class="line">      &#125;);</span><br><span class="line"> </span><br><span class="line">      <span class="comment">// Install a cancellation handler to free the descriptor</span></span><br><span class="line">      <span class="comment">// and the stored string.</span></span><br><span class="line">      dispatch_source_set_cancel_handler(source, ^&#123;</span><br><span class="line">          <span class="keyword">char</span>* fileStr = (<span class="keyword">char</span>*)dispatch_get_context(source);</span><br><span class="line">          free(fileStr);</span><br><span class="line">          close(fd);</span><br><span class="line">      &#125;);</span><br><span class="line"> </span><br><span class="line">      <span class="comment">// Start processing events.</span></span><br><span class="line">      dispatch_resume(source);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span></span><br><span class="line">      close(fd);</span><br><span class="line"> </span><br><span class="line">   <span class="keyword">return</span> source;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="监控信号">监控信号</h3>
<p>UNIX信号允许从一个程序外对其进行操纵。一个程序可以接收许多不同类型的信号，从不可恢复的错误（如非法指令）到重要信息的通知（如一个子进程退出时）。传统上，程序使用<code>sigaction</code>函数来配置一个信号处理函数，该函数在信号到达后立即同步处理。如果你只是想得到信号到达的通知，而不是真的想处理信号，你可以使用一个信号调度源来异步处理信号。</p>
<p>信号调度源不能替代使用<code>sigaction</code>函数配置的同步信号handler。同步信号handler实际上可以捕获一个信号并防止它终止程序。信号调度源允许你只监控信号的到达。此外，你不能使用信号调度源来检索所有类型的信号。具体来说，你不能用它们来监控<code>SIGILL</code>、<code>SIGBUS</code>和<code>SIGSEGV</code>信号。</p>
<p>因为信号调度源是在调度队列上异步执行的，所以它们不受一些与同步信号handler的限制。例如，你可以从信号调度源的事件handler中调用的函数。这种灵活性增加的代价是，在信号到达和调度源的事件handler被调用之间可能会有一些延迟。</p>
<p>清单4-5显示了如何配置一个信号调度源来处理<code>SIGHUP</code>信号。调度源的事件handler调用了<code>MyProcessSIGHUP</code>函数，你可以在此实现自己的处理信号逻辑。</p>
<p><strong>清单4-5</strong> 配置block监控信号</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> InstallSignalHandler()</span><br><span class="line">&#123;</span><br><span class="line">   <span class="comment">// Make sure the signal does not terminate the application.</span></span><br><span class="line">   signal(SIGHUP, SIG_IGN);</span><br><span class="line"> </span><br><span class="line">   <span class="built_in">dispatch_queue_t</span> queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>);</span><br><span class="line">   dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGHUP, <span class="number">0</span>, queue);</span><br><span class="line"> </span><br><span class="line">   <span class="keyword">if</span> (source)</span><br><span class="line">   &#123;</span><br><span class="line">      dispatch_source_set_event_handler(source, ^&#123;</span><br><span class="line">         MyProcessSIGHUP();</span><br><span class="line">      &#125;);</span><br><span class="line"> </span><br><span class="line">      <span class="comment">// Start processing signals</span></span><br><span class="line">      dispatch_resume(source);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果你正在为一个自定义的框架开发代码，使用信号调度源的一个好处是代码可以独立于任何链接到它的程序来监控信号。信号调度源不会干扰其他调度源或程序可能配置的任何同步信号handler。</p>
<h3 id="监控进程">监控进程</h3>
<p>进程调度源可以让你监控一个特定进程的行为，并作出适当的响应。一个父进程可以使用这种调度源来监视它所创建的任何子进程。例如，父进程可以用它来监视一个子进程的结束。同样地，一个子进程可以用它来监视它的父进程，并在父进程退出时退出。</p>
<p>清单4-6显示了配置一个调度源以监视父进程终止的步骤。当父进程终止时，调度源设置一些内部状态信息，让子进程知道它应该退出。(程序需要实现<code>MySetAppExitFlag</code>函数来为终止设置一个适当的标志。) 由于调度源自主运行，因此持有自己，它也会在预期程序关闭的情况下取消和释放自己。</p>
<p><strong>清单4-6</strong> 监控父进程的终止</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> MonitorParentProcess()</span><br><span class="line">&#123;</span><br><span class="line">   pid_t parentPID = getppid();</span><br><span class="line"> </span><br><span class="line">   <span class="built_in">dispatch_queue_t</span> queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>);</span><br><span class="line">   dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC,</span><br><span class="line">                                                      parentPID, DISPATCH_PROC_EXIT, queue);</span><br><span class="line">   <span class="keyword">if</span> (source)</span><br><span class="line">   &#123;</span><br><span class="line">      dispatch_source_set_event_handler(source, ^&#123;</span><br><span class="line">         MySetAppExitFlag();</span><br><span class="line">         dispatch_source_cancel(source);</span><br><span class="line">         dispatch_release(source);</span><br><span class="line">      &#125;);</span><br><span class="line">      dispatch_resume(source);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="取消调度源">取消调度源</h2>
<p>调度源一直处于活动状态，直到你使用<code>dispatch_source_cancel</code>函数显式取消它们。取消一个调度源会停止新事件的传递，并且不能被撤销。因此，通常取消一个调度源，然后就立即释放它，如下所示：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> RemoveDispatchSource(dispatch_source_t mySource)</span><br><span class="line">&#123;</span><br><span class="line">   dispatch_source_cancel(mySource);</span><br><span class="line">   dispatch_release(mySource);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>取消一个调度源是一个异步操作。尽管在你调用<code>dispatch_source_cancel</code>函数后，没有新的事件被处理，但已经被调度源处理的事件还是继续被处理。在处理完任何最终事件后，如果有取消handler，调度源会执行其取消handler。</p>
<p>取消handler是你释放内存或清理代表调度源获取的任何资源的机会。如果调度源使用描述符或mach端口，你必须提供一个取消handler，以便在取消发生时关闭描述符或销毁端口。其他类型的调度源不需要取消handler，但如果你将任何内存或数据与调度源关联，仍应提供。例如，如果你在调度源的上下文指针中存储数据，你应提供取消handler。关于取消handler的更多信息，可参阅<a target="_blank" rel="noopener" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW14">Installing a Cancellation Handler</a>。</p>
<h2 id="暂停和恢复调度源">暂停和恢复调度源</h2>
<p>你可以使用<code>dispatch_suspend</code>和<code>dispatch_resume</code>方法暂停和恢复调度源事件的传递。这些方法为调度对象增加和减少暂停计数。因此，你必须在每次平衡调用<code>dispatch_suspend</code>与调用<code>dispatch_resume</code>。</p>
<p>当暂停一个调度源时，任何在该调度源被暂停时发生的事件都会被收集起来，直到队列恢复。当队列恢复时，不是发送所有的事件，而是在发送前将这些事件合并成一个单一的事件。例如，如果你正在监控一个文件的名称变化，发送的事件将只包括最后的名称变化。以这种方式合并事件，可以防止它们在队列中堆积，并在工作恢复时让你的程序应付不来。</p>
<h2 id="总结">总结</h2>
<ul>
<li>调度源用于监听底层（系统、内核）事件，实现处理事件异步回调。既然是用于监听，对应的就该主动取消。</li>
<li>在Swift中，根据调度源类型，有对应的协议。但创建都是使用DispatchSource对应的make类工厂方法创建特定类型的调度源。这样接收的调度源返回值就可以调用特定类型协议的具体方法。</li>
<li>调度源的通用方法都定义在DispatchSourceProtocol。
<ul>
<li>配置：<code>setRegistrationHandler</code>、<code>setEventHandler</code>、<code>setCancelHandler</code></li>
<li>基本操作：<code>activate</code>、<code>cancel</code>、<code>suspend</code>、<code>resume</code>、</li>
</ul></li>
</ul>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Apple/" rel="tag"># Apple</a>
              <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"># 多线程</a>
              <a href="/tags/Concurrency-Programming-Guide/" rel="tag"># Concurrency Programming Guide</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/concurrency_pg_dispatch_queues/" rel="prev" title="Concurrency Programming Guide：调度队列">
      <i class="fa fa-chevron-left"></i> Concurrency Programming Guide：调度队列
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/concurrency_pg_migrating_away_from_threads/" rel="next" title="Concurrency Programming Guide：迁移线程代码">
      Concurrency Programming Guide：迁移线程代码 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E8%B0%83%E5%BA%A6%E6%BA%90"><span class="nav-text">关于调度源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E8%B0%83%E5%BA%A6%E6%BA%90"><span class="nav-text">创建调度源</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BC%96%E5%86%99%E5%92%8C%E9%85%8D%E7%BD%AE%E4%B8%80%E4%B8%AA%E4%BA%8B%E4%BB%B6handler"><span class="nav-text">编写和配置一个事件Handler</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%85%8D%E7%BD%AE%E5%8F%96%E6%B6%88handler"><span class="nav-text">配置取消Handler</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BF%AE%E6%94%B9%E7%9B%AE%E6%A0%87%E9%98%9F%E5%88%97"><span class="nav-text">修改目标队列</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E8%81%94%E8%87%AA%E5%AE%9A%E4%B9%89%E6%95%B0%E6%8D%AE%E4%B8%8E%E8%B0%83%E5%BA%A6%E6%BA%90"><span class="nav-text">关联自定义数据与调度源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B0%83%E5%BA%A6%E6%BA%90%E7%9A%84%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86"><span class="nav-text">调度源的内存管理</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B0%83%E5%BA%A6%E6%BA%90%E7%A4%BA%E4%BE%8B"><span class="nav-text">调度源示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%AE%9A%E6%97%B6%E5%99%A8"><span class="nav-text">创建定时器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%8E%E6%8F%8F%E8%BF%B0%E7%AC%A6%E4%B8%AD%E8%AF%BB%E5%8F%96%E6%95%B0%E6%8D%AE"><span class="nav-text">从描述符中读取数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8A%8A%E6%95%B0%E6%8D%AE%E5%86%99%E5%85%A5%E6%8F%8F%E8%BF%B0%E7%AC%A6%E4%B8%AD"><span class="nav-text">把数据写入描述符中</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9B%91%E6%8E%A7%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E5%AF%B9%E8%B1%A1"><span class="nav-text">监控文件系统对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9B%91%E6%8E%A7%E4%BF%A1%E5%8F%B7"><span class="nav-text">监控信号</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9B%91%E6%8E%A7%E8%BF%9B%E7%A8%8B"><span class="nav-text">监控进程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%96%E6%B6%88%E8%B0%83%E5%BA%A6%E6%BA%90"><span class="nav-text">取消调度源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9A%82%E5%81%9C%E5%92%8C%E6%81%A2%E5%A4%8D%E8%B0%83%E5%BA%A6%E6%BA%90"><span class="nav-text">暂停和恢复调度源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="權咚"
      src="/images/icon.png">
  <p class="site-author-name" itemprop="name">權咚</p>
  <div class="site-description" itemprop="description">🤘🤯👾</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">84</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/bqlin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;bqlin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/hearingdog" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;hearingdog" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/metal-reference-translation" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;metal-reference-translation" rel="noopener" target="_blank">Metal内参</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/wwdc21" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;wwdc21" rel="noopener" target="_blank">WWDC21 内参</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">權咚</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">279k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '7ed324dbfd2741c35c0e',
      clientSecret: '75a59e1f6a55202c4a1b0ec3570ad5b5dccbc390',
      repo        : 'bqlin.github.io',
      owner       : 'bqlin',
      admin       : ['bqlin'],
      id          : 'cfc19e356f13ae4ac01f787526ce4894',
        language: 'zh-CN',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","vOffset":-100},"mobile":{"show":false,"scale":0.5},"log":false});</script></body>
</html>
